package com.uyayo.core.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.uyayo.framework.web.constants.WebConstants;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uyayo.framework.common.util.CaptchaUtil;
import com.uyayo.framework.common.util.io.FileUtil;

/**
 * 
 * <p>
 * Title: CaptchaController
 * </p>
 * <p>
 * Description:验证码的Controller
 * </p>
 * <p>
 * Company: www.lelekeji.com
 * </p>
 * 
 * @author 乐乐科技.胡逢君
 * @date 2016-4-23下午4:03:35
 * @version 1.0
 */
@RestController
@RequestMapping("captcha")
public class CaptchaController{
	
	/** 
	 * 功能：打开login.jsp的时候获得随机的验证码图片 
	 *  
	 * @return 
	 * @throws IOException 
	 */
	@GetMapping()
	public void getCaptcha(HttpServletRequest request,HttpServletResponse response) throws IOException {
		CaptchaUtil vcu = CaptchaUtil.Instance();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		ByteArrayInputStream input = vcu.getImage();
		request.getSession().setAttribute(WebConstants.CAPTCHA_SESSION,vcu.getCaptcha());  // 取得随机字符串放入HttpSession
		FileUtil.writeStream(input, output, 1024);
		try{
            ServletOutputStream out = response.getOutputStream();  
            output.writeTo(out);  
        } catch (IOException e) {  
            e.printStackTrace();  
        }
    }
	
	
	/** 
	 * 功能：打开login.jsp的时候获得随机的验证码图片 
	 *  
	 * @return 
	 * @throws IOException 
	 */
	@RequestMapping("check")
	public Boolean check(HttpSession session,String captcha) throws IOException {
		String captchaSession = (String) session.getAttribute(WebConstants.CAPTCHA_SESSION);

		if(captcha !=null && !captcha.equals(captchaSession)){
			return false;
		}else{
			return true;
		}
    }
	
}
